import React, { Component, Fragment } from 'react';
import router from 'umi/router';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Table, Tabs, Input, message, Modal, Tooltip } from 'antd';
import _ from 'lodash';
import { connect } from 'dva';
import * as apis from '@/services/SystemMgr';
import * as utils from '@/utils/utils';
import styles from './index.less';
import Mpagination from '../components/Mpagination';
import AddRole from './pages/AddRole';
import SetFunctionJurisdiction from './pages/SetFunctionJurisdiction';
import SetDataJurisdiction from './pages/SetDataJurisdiction';
import AuthorizedButton from '@/components/AuthorizedButton';

const { TabPane } = Tabs;
const { Search } = Input;
const { confirm } = Modal;

class LimitAdministration extends Component {
  constructor() {
    super();
    this.state = {
      loading: true,
      total: '0', // 总条数
      pageSize: '20', // 每页显示条数
      current: '1', // 当前页数
      pages: '0', // 总页数
      searchValue: '',
      selectedRowKeys: [],
      deleteVisible: false,
      confirmLoading: false,
      roleId: '',
      columns: [],
      dataSource: [],
    };
  }

  componentDidMount() {
    if (this.props.location.query.activeKey === 'Job_group') {
      if (this.props.location.state) {
        this.getPotGroupAuthPageUsing(
          this.props.location.state.current,
          this.props.location.state.searchValue,
          this.props.location.state.pageSize,
        );
        this.setState({
          searchValue: this.props.location.state.searchValue,
        });
      } else {
        this.getPotGroupAuthPageUsing();
      }
    } else if (this.props.location.query.activeKey === 'special_role') {
      if (this.props.location.state) {
        this.getRolePageListUsing(
          this.props.location.state.current,
          this.props.location.state.pageSize,
        );
      } else {
        this.getRolePageListUsing();
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      loading: true,
      titleTree: [],
      dataSource: [],
      total: '0', // 总条数
      pageSize: '20', // 每页显示条数
      current: '1', // 当前页数
      pages: '0', // 总页数
    });
    if (nextProps.location.query.activeKey === 'Job_group') {
      this.getPotGroupAuthPageUsing();
    } else if (nextProps.location.query.activeKey === 'special_role') {
      this.getRolePageListUsing();
    }
  }

  // 请求岗位组的数据
  async getPotGroupAuthPageUsing(
    current = '1',
    searchValue = '-1',
    pageSize = this.state.pageSize,
  ) {
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        key: 'key',
        width: 50,
        align: 'center',
      },
      {
        title: '岗位组名称',
        dataIndex: 'name',
        key: 'name',
        width: 150,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '级别',
        dataIndex: 'level',
        key: 'level',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '授权方式',
        dataIndex: 'empower',
        key: 'empower',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '操作',
        align: 'center',
        width: 200,
        render: (text, record) => (
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div>
              <Button
                type="link"
                onClick={() => {
                  router.push({
                    pathname: '/SystemManage/limitAdministration/job_detail',
                    query: {
                      name: escape(record.name),
                      id: record.code,
                      current: this.state.current,
                      pageSize: this.state.pageSize,
                      searchValue: this.state.searchValue,
                    },
                  });
                }}
              >
                岗位明细
              </Button>
            </div>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_post_functionLimitsOfAuthority">
              <SetFunctionJurisdiction
                info="岗位组信息"
                infoName="岗位组名称:"
                recordName={record.name}
                Id={record.code}
              />
            </AuthorizedButton>

            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_isEmpower">
              <a
                onClick={
                  record.empower === ''
                    ? () =>
                        utils.showConfirm(
                          () => this.handleSingleEmpower(record.code, record.empower),
                          '自动授权岗位？',
                          '确定后授权该岗位组下岗位的数据权限',
                        )
                    : () =>
                        utils.showConfirm(
                          () => this.handleSingleEmpower(record.code, record.empower),
                          '取消授权岗位？',
                          '取消后该岗位组下的岗位将没数据权限',
                        )
                }
              >
                {record.empower === '自动授权' ? '取消授权' : '自动授权'}
              </a>
            </AuthorizedButton>
          </span>
        ),
      },
    ];

    const regPos = /^\d+(\.\d+)?$/;
    let jobDefinitionsId;
    let jobDefinitionsName;
    if (regPos.test(searchValue)) {
      jobDefinitionsId = searchValue;
      jobDefinitionsName = '-1';
    } else if (searchValue === '-1') {
      jobDefinitionsName = '-1';
      jobDefinitionsId = '-1';
    } else {
      jobDefinitionsName = searchValue;
      jobDefinitionsId = '-1';
    }
    const params = {
      current,
      jobDefinitionsId,
      jobDefinitionsName,
      pageSize,
    };
    const getPotGroupAuthPageUsing = await apis.getPotGroupAuthPageUsingGET({ params });
    if (getPotGroupAuthPageUsing && getPotGroupAuthPageUsing.code === 1) {
      const { data } = getPotGroupAuthPageUsing;
      const dataSource = [];
      data.list.forEach((item, index) => {
        const obj = {
          key: data.pageSize * (data.current - 1) + index + 1,
          name: item.jobDefinitionsName,
          code: item.jobDefinitionsId,
          level: item.z9121cjt,
          state: item.jobDefinitionStatus,
          type: item.jobDefinitionType,
          empower: item.authMode,
        };
        dataSource.push(obj);
        return dataSource;
      });

      this.setState({
        columns,
        dataSource,
        total: data.total, // 总条数
        pageSize: data.pageSize, // 每页显示条数
        current: data.current, // 当前页数
        pages: data.pages, // 总页数
        loading: false,
      });
    }
  }

  // 请求特殊角色的数据
  async getRolePageListUsing(current = '1', pageSize = this.state.pageSize) {
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        key: 'key',
        align: 'center',
        width: 50,
      },
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        width: 200,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '角色描述',
        dataIndex: 'describe',
        key: 'describe',
        width: 200,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '创建人',
        dataIndex: 'addName',
        key: 'addName',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '时间',
        dataIndex: 'operation',
        key: 'operation',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '用户数/个',
        dataIndex: 'userNum',
        key: 'userNum',
        width: 100,
        render: text => (
          <Tooltip placement="topLeft" title={text}>
            <div
              style={{
                width: '100%',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
              }}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '操作',
        align: 'center',
        width: 300,
        render: (text, record) => (
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_distributionUser">
              <a
                onClick={() => {
                  router.push({
                    pathname: '/SystemManage/limitAdministration/assign_users',
                    query: {
                      describe: escape(record.describe),
                      name: escape(record.name),
                      id: record.id,
                      current: this.state.current,
                      pageSize: this.state.pageSize,
                    },
                  });
                }}
              >
                分配用户
              </a>
            </AuthorizedButton>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_roles_functionLimitsOfAuthority">
              <SetFunctionJurisdiction
                info="角色组信息"
                infoName="角色名称:"
                recordName={record.name}
                describe={record.describe}
                Id={record.id}
              />
            </AuthorizedButton>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_roles_dataLimitsOfAuthority">
              <SetDataJurisdiction type="roleId" name={record.name} Id={record.id} />
            </AuthorizedButton>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_editRoles">
              <AddRole
                update={() => this.getRolePageListUsing(this.state.current, this.state.pageSize)}
                roleName={record.name}
                roleDesc={record.describe}
                roleId={record.id}
                btnType="link"
                value="编辑"
                title="编辑角色"
              />
            </AuthorizedButton>
            <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_deleteRoles">
              <a
                onClick={() =>
                  utils.showConfirm(
                    () => this.handleOk(record),
                    '删除角色',
                    '删除后将没有该特殊角色',
                  )
                }
              >
                删除
              </a>
            </AuthorizedButton>
          </span>
        ),
      },
    ];

    const params = {
      current,
      pageSize,
    };
    const getPotGroupAuthPageUsing = await apis.getRolePageListUsingGET({ params });
    if (getPotGroupAuthPageUsing && getPotGroupAuthPageUsing.code === 1) {
      const { data } = getPotGroupAuthPageUsing;
      const dataSource = [];
      data.list.forEach((item, index) => {
        const obj = {
          id: item.roleId,
          key: data.pageSize * (data.current - 1) + index + 1,
          name: item.roleName,
          describe: item.roleDesc,
          addName: item.createby,
          operation: item.createStr,
          userNum: item.userNum,
        };
        dataSource.push(obj);
      });
      this.setState({
        columns,
        dataSource,
        total: data.total, // 总条数
        pageSize: data.pageSize, // 每页显示条数
        current: data.current, // 当前页数
        pages: data.pages, // 总页数
        loading: false,
      });
    }
  }

  // tab参数添加至url
  handleTabType = activeKey => {
    router.push({
      pathname: '/SystemManage/limitAdministration',
      query: {
        activeKey,
      },
    });
  };

  // 岗位组单个授权
  handleSingleEmpower = async (code, empower) => {
    const params =
      empower !== ''
        ? {
            deletePositionGroupIds: [code],
            savePositionGroupIds: [],
          }
        : {
            savePositionGroupIds: [code],
            deletePositionGroupIds: [],
          };

    const data = await apis.createSysPositionGroupAuthorizeUsingPOST({ data: params });
    if (data.code === 1) {
      this.getPotGroupAuthPageUsing(this.state.current, this.state.searchValue);
    }
  };

  // 岗位组批量授权
  handleBatchEmpower = () => {
    const self = this;
    const { selectedRowKeys } = self.state;
    const savePositionGroupIds = selectedRowKeys;
    const params = {
      deletePositionGroupIds: [],
      savePositionGroupIds,
    };
    confirm({
      title: '批量自动授权',
      content:
        savePositionGroupIds.length > 0
          ? `当前已选${selectedRowKeys.length}条，点击确定批量授权岗位自动授权数据权限`
          : '没有选中的岗位组。',
      okText: '确定',
      cancelText: savePositionGroupIds.length > 0 ? '取消' : '返回选择',
      onOk() {
        if (savePositionGroupIds.length <= 0) {
          message.warning('没有选中的岗位组!');
        } else {
          apis.createSysPositionGroupAuthorizeUsingPOST({ data: params }).then(data => {
            if (data.code === 1) {
              self.getPotGroupAuthPageUsing(self.state.current, self.state.searchValue);
              self.setState({ selectedRowKeys: [] });
              message.success(data.message);
            }
          });
        }
      },
    });
  };

  // 分页切换
  handlePaginationChange = (current, pageSize = 20) => {
    const { location } = this.props;
    this.setState({
      titleTree: [],
      dataSource: [],
      loading: true,
    });
    if (location.query.activeKey === 'Job_group') {
      this.getPotGroupAuthPageUsing(`${current}`, this.state.searchValue, pageSize);
    } else if (location.query.activeKey === 'special_role') {
      this.getRolePageListUsing(`${current}`, pageSize);
    }
  };

  // 获取搜索框的查询岗位组
  handleSearchChange = value => {
    this.setState({
      searchValue: value,
      loading: true,
    });
    this.getPotGroupAuthPageUsing('1', value);
  };

  // 删除特殊角色
  handleOk = async row => {
    const userNum = row.userNum * 1; // 特殊角色下存在的用户
    if (userNum > 0) {
      confirm({
        title: '该特殊角色下存在分配用户不可删除',
        content: '如要删除先移除该特殊角色下分配的用户',
        okText: '跳转分配用户界面',
        cancelText: '取消',
        onOk() {
          router.push({
            pathname: '/SystemManage/limitAdministration/assign_users',
            query: {
              describe: escape(row.describe),
              name: escape(row.name),
              id: row.id,
            },
          });
        },
      });
    } else {
      const deleteRoleByIdUsing = await apis.deleteRoleByIdUsingDELETE({
        params: {
          roleId: row.id,
        },
      });
      if (deleteRoleByIdUsing.code === 1) {
        this.getRolePageListUsing().then(() => {
          message.success('删除成功！');
        });
      } else {
        message.error('删除失败！');
      }
    }
  };

  // 特色角色 model取消
  handleCancel = () => {
    this.setState({
      deleteVisible: false,
    });
  };

  // 监听选中的岗位，并获取选中的id
  onSelectChange = selectedRowKeys => {
    this.setState({
      selectedRowKeys,
    });
  };

  // 搜索框输入
  onIptChangeVal = evt => {
    this.setState({
      searchValue: evt.target.value,
    });
  };

  // 对的筛选条件
  tabBarExtraContent = activeKey => {
    let dom = <></>;
    if (!activeKey || activeKey === '') {
      this.handleTabType('Job_group');
      return dom;
    }
    if (activeKey === 'Job_group') {
      dom = (
        <Fragment>
          <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_isEmpower">
            <Button type="primary" onClick={this.handleBatchEmpower}>
              批量自动授权
            </Button>
          </AuthorizedButton>
          <Search
            value={this.state.searchValue}
            onChange={this.onIptChangeVal}
            placeholder="搜索名称/编码"
            onSearch={this.handleSearchChange}
            style={{ width: 265, marginLeft: 10 }}
          />
        </Fragment>
      );
    } else if (activeKey === 'special_role') {
      dom = (
        <AuthorizedButton authority="systemConfig_LimitsOfAuthorityManage_addRoles">
          <AddRole
            update={() => this.getRolePageListUsing()}
            value="新增角色"
            title="新增角色"
            roleName=""
            roleDesc=""
            btnType="primary"
          />
        </AuthorizedButton>
      );
    }
    return dom;
  };

  render() {
    const { loading, selectedRowKeys, columns, dataSource } = this.state;
    const { Permissions, location } = this.props;
    const tableHeight = document.body.clientHeight - 255;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const { activeKey } = location.query;
    return (
      <div className={styles.LimitAdministration}>
        <PageHeaderWrapper breadcrumb={null} title="权限管理">
          <Card>
            <Tabs
              activeKey={activeKey}
              onChange={key => {
                this.handleTabType(key);
              }}
              animated={false}
            >
              <TabPane tab="岗位组" key="Job_group" />
              <TabPane tab="特殊角色" key="special_role" />
            </Tabs>
            <div className="tabBarExtraContent">{this.tabBarExtraContent(activeKey)}</div>
            <Table
              rowSelection={
                _.indexOf(Permissions.buttons, 'button_106030101') > -1 && activeKey === 'Job_group'
                  ? rowSelection
                  : null
              }
              rowKey={activeKey === 'Job_group' ? 'code' : 'key'}
              columns={columns}
              dataSource={dataSource}
              pagination={false}
              bordered
              size="middle"
              scroll={{ y: tableHeight }}
              loading={loading}
            />
            <Mpagination
              model={
                _.indexOf(Permissions.buttons, 'button_106030101') > -1 && activeKey === 'Job_group'
                  ? `已选中${selectedRowKeys.length}条`
                  : ''
              }
              total={this.state.total}
              pageSize={this.state.pageSize}
              current={this.state.current}
              pages={this.state.pages}
              onShowSizeChange={(current, pageSize) =>
                this.handlePaginationChange(current, pageSize)
              }
              handlePaginationChange={this.handlePaginationChange}
              loading={this.state.loading}
            />
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default connect(({ Permissions }) => ({
  Permissions,
}))(LimitAdministration);
